import { loginByCode, getUserInfo } from "../../api/user";

export default
	{
		state: {
			access_token: '',
			userInfo: {},
		},
		mutations: {
			SET_USER_TOKEN: (state, access_token) => {
				state.access_token = access_token
			},
			SET_USER_INFO: (state, info) => {
				state.userInfo = info
			}
		},
		actions: {
			/**
			 * 授权登录
			 */
			LoginByCode({
				commit
			}) {
				return new Promise((resolve, reject) => {
					uni.login({
						success: loginRes => {
							loginByCode(loginRes.code).then(res => {
								uni.setStorageSync('access_token', res.data.token)
								commit('SET_USER_TOKEN', res.data.token)
								resolve(res)
							}).catch(err => {
								reject(err)
							})
						},
						fail: loginErr => {
							reject(loginErr)
						}
					});
				})
			},
			async ListenLogingStatus({ state }) {
				let count = 0
				return new Promise((resolve, reject) => {
					if (state.access_token) {
						resolve()
					} else {
						const timer = setInterval(() => {
							count++
							if (state.access_token) {
								clearInterval(timer)
								resolve()
							} else if (count > 20) {
								clearInterval(timer)
								reject()
							}
						}, 100);
					}
				})
			},
			GetUserInfo({ commit }) {
				getUserInfo().then(({ data }) => {
					commit('SET_USER_INFO', data)
				})
			}
		}
	}
